package cn.codeforfun.mq.queue;

import cn.codeforfun.jfinalplugin.activemq.core.JFinalQueue;

import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.TextMessage;


/**
 * Created by Administrator on 2016/3/26.
 */
public class ActiveMqQueue extends JFinalQueue {

    MessageListener listener;

    public ActiveMqQueue(String queueName,MessageListener listener) {
        mq(queueName).listener(listener);
    }

    public ActiveMqQueue(String queueName) {
        mq(queueName).listener(queueName);//queueName作为listenerName
    }

    public ActiveMqQueue() {
        //提供空对象用于链式
    }

    public ActiveMqQueue mq(String queueName) {
        init(queueName);
        return this;
    }

    public ActiveMqQueue listener(MessageListener listener) {
        this.listener = listener;
        return this;
    }

    public ActiveMqQueue listener(String listenerName){
        this.listener = (msg) -> {
            try {
                System.out.println(listenerName+"收到消息:"
                        + ((TextMessage) msg).getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        return this;
    }

    public void run() {
        try {
            getConsumer().setMessageListener(
                    listener(getQueueName()).listener);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}
